import Vue from 'vue';
import App from './App';
import router from './router';
import ElementUI from 'element-ui';
import NProgress from 'nprogress';//状态条
import axios from 'axios';
import VueAxios from 'vue-axios';
import storage from "./utils/storage";//LocalStorage操作
import store from './utils/store';
import Moment from 'moment';//时间格式化npm install moment --save

//一些样式
import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css';
import 'nprogress/nprogress.css';
import './assets/css/bootstrap.min.css';
import './assets/css/main.css';
import './assets/css/reset.css';
import './assets/css/index.css';


Vue.use(ElementUI);
Vue.use(VueAxios, axios);

Vue.prototype.$axios = axios;
Vue.prototype.$store = store;
Vue.prototype.moment = Moment;
Vue.prototype.$storage = storage;
Vue.config.productionTip = false;


router.beforeEach((to, from, next) => {
    NProgress.start();//开启进度条
    if (to.meta.title) document.title = to.meta.title;//动态化每个页面的标题
    const token = storage.get('token');
    const whiteList = ['Login'];
    if(token){
        //登陆之后不能直接访问登陆页面
        if(to.matched.some( m => m.meta.login)){
            next({name:'Main'})
        }else{
            //是否需要重新获取用户数据
            if(store.getters.user){
                next();
            }else{
                store.dispatch('userInfo').then((res)=>{
                    store.dispatch('generateRoutes',res).then(()=>{
                        router.addRoutes(store.getters.routers); // 动态添加可访问路由表
                        next({ ...to });//hack方法 确保addRoutes已完成
                    });
                }).catch(()=>{
                    store.dispatch('userLogout').then(() =>{
                        next({name:'Login'})
                    });
                });
            }
        }
    }else{
        if(whiteList.includes(to.name)){
            next();
        }else{
            next({name:'Login'})// token不存在的情况全部重定向到登录页
        }
    }
});
NProgress.configure({ showSpinner: false });//取消右上角的进度环
router.afterEach(transition => {
    NProgress.done();//关闭进度条
});
//axios请求自动添加headers信息
axios.interceptors.request.use(function (config) {
    const token = storage.get('token');
    if(token){
        //配置header的token信息
        config.headers['Authorization'] = 'Bearer ' + token;
        config.headers['Accept'] = 'application/json';
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});
new Vue({
    el: '#app',
    router,
    components: {App},
    template: '<App/>'
})
